#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
  pid_t id = fork();
  if(id < 0){
    perror("fork error!\n");
    return 1;
  }
  if(id == 0){
    int ret = 0;
    //child, 1
    int count = 0;
    while(count < 20){
      printf("child [%d] is running...\n", getpid());
      sleep(1);
      count++;
    }
    // code 2
    // ret = 1
    // code 3
    // ret = 2;
    //
    //int a = 1/0;
    
    exit(ret);
  }

  //father
  printf("father wait before!\n");
  int st = 0;
  pid_t ret = 0;
  do{
      ret = waitpid(id, &st, WNOHANG); //wait(NULL)
      if(ret == 0){
        //sleep(1);

        printf("child is not quit, check later!\n");
        continue;
      }
      if(ret > 0){
        if(WIFEXITED(st)){
          printf("exit code : %d\n", WEXITSTATUS(st));
        }
        else{
          printf("child exit error!\n");
        }
        //printf("wait success!\n");
        //printf("st: %d\n", st);
        //printf("child exit signal: %d\n", st & 0x7F); //111 1111
        //printf("child exit code: %d\n", (st>>8)&0xff);
        //if(st & 0x7F){
        //  printf("child run error!\n");
        //}
        //else{
        //  int code=((st>>8) & 0xff);
        //  if(code){
        //    printf("child run success, but result is not right!: code : %d\n", code);
        //  }
        //  else{
        //    printf("child run success, result is right!: code : %d\n", code);
        //  }
        //}
        break;
      }
      else{
        printf("wait failed!\n");
        break;
      }
  }while(1);
  printf("father wait after!\n");
 // else{
 //   //parent

 // }
}





